package com.itsu.mongodb.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.itsu.interfaces.entity.Friends;
import com.itsu.interfaces.entity.TimeLine;
import com.itsu.interfaces.service.TimeLineService;
import com.itsu.pojo.constants.Constants;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;

import java.util.List;

@Service
public class TimeLineServiceImpl implements TimeLineService {

    @Autowired
    MongoTemplate mongoTemplate;


    @Override
    @Async
    public void saveFriendsTimeLine(ObjectId publishId, Long uid) {
        List<Friends> friendsList = mongoTemplate.find(Query.query(Criteria.where("userId").is(uid)), Friends.class);

        List<Long> friendIdList = CollUtil.getFieldValues(friendsList, "friendId", Long.class);

        TimeLine timeLine = new TimeLine();
        timeLine.setId(new ObjectId());
        timeLine.setPublishId(publishId);
        timeLine.setUserId(uid);
        timeLine.setDate(System.currentTimeMillis());
        for (Long friendId : friendIdList) {
            mongoTemplate.save(timeLine, Constants.Timeline_DATABASE_NAME + friendId);
        }

    }
}
